import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Button, Steps, Icon, Menu, Dropdown, Progress, Tooltip, Tag, Card } from 'antd';
import styles from '../Users.css';
import Factory from '../../factory';
import dataEditCreate from '../../addons/DataEdit'
import dataTableCreate from '../../addons/DataTable'
import FileUpLoad from '../../addons/FileUpLoad'
import SYJCLRSQ_MXForm from './SYJCLRSQ_MXForm'
const daoName = "COMP_JC";
const ButtonGroup = Button.Group;
const renderStep = (data) => {
    const { progress, status } = data
    const percent = Math.round(progress)
    return <Progress percent={percent} size="small" status={status === "" ? "normal" : status} />
};

const controls = [
    { name: 'JCRW', required: true, type: 'text', label: '任务名称', dataType: "string", grid: 24 / 24 },
    {
        name: "SSTX", label: "所属条线", required: true,
        data: [
            { value: '1', label: '公司银行线' },
            { value: '2', label: '同业票据线' },
            { value: '3', label: '交易银行线' }
        ],
        grid: 24 / 24, type: "select"
    },
    { name: 'CNRQ', required: true, type: 'text', label: '收益承诺日期', dataType: "string", grid: 24 / 24, placeholder: "按YYYYMM格式输入,例如:202401", min: 6, max: 6 },
    {
        name: "JYDW", required: true, label: "经营单位", type: "search", grid: 24 / 24,
        fetch: {
            daoName: "Organization", searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "Name"
        },
        dataType: "string", placeholder: '请输入网点号或网点名称...'
    },
    {
        name: "FZRNO", required: true, label: "支行负责人", type: "search", grid: 24 / 24,
        fetch: {
            daoName: "UserSel", searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "No"
        },
        dataType: "string", placeholder: '请输入工号或名称...'
    },
    {
        name: "EMNO1", required: true, label: "客户经理1", type: "search", grid: 24 / 24,
        fetch: {
            daoName: "UserSel", searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "No"
        },
        dataType: "string", placeholder: '请输入工号或名称...'
    },
    {
        name: "EMNO2", label: "客户经理2", type: "search", grid: 24 / 24,
        fetch: {
            daoName: "UserSel", searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "No"
        },
        dataType: "string", placeholder: '请输入工号或名称...'
    },
    {
        name: "EMNO3", label: "客户经理3", type: "search", grid: 24 / 24,
        fetch: {
            daoName: "UserSel", searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "No"
        },
        dataType: "string", placeholder: '请输入工号或名称...'
    },
    { name: 'BZ', type: 'text', label: '备注', dataType: "string", grid: 24 / 24 },
]
const controls2 = [
    { name: 'JCRW', required: true, type: 'text', label: '任务名称', dataType: "string", grid: 24 / 24 },
    { name: 'SSTX', required: true, type: 'text', label: '所属条线', dataType: "string", grid: 24 / 24 },
    { name: 'CNRQ', required: true, type: 'text', label: '收益承诺日期', dataType: "string", grid: 24 / 24 },
    { name: 'JYDW', required: true, type: 'text', label: '经营单位', dataType: "string", grid: 24 / 24 },
    { name: 'FZR', required: true, type: 'text', label: '支行负责人', dataType: "string", grid: 24 / 24 },
    { name: 'KHJL1', required: true, type: 'text', label: '客户经理1', dataType: "string", grid: 24 / 24 },
    { name: 'KHJL2', required: true, type: 'text', label: '客户经理2', dataType: "string", grid: 24 / 24 },
    { name: 'KHJL3', required: true, type: 'text', label: '客户经理3', dataType: "string", grid: 24 / 24 },
    { name: 'BZ', required: true, type: 'text', label: '备注', dataType: "string", grid: 24 / 24 },
    { name: 'FID', required: true, type: 'text', label: '备注', dataType: "string", grid: 24 / 24 },
]
const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
const Step = Steps.Step

class SYJCLRSQForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataChange: false,
            range: "firstdoing",
            stepTitle: "",
            canEdit: false,
            cunm: "",
            isClick: false,
            mKey: 0,
            rwid: 0,
            cdisplay: "none",
            isShowBtn: true,
        };
    }
    componentDidMount() {
        this.loadData()
        this.loadOptionData()
    }
    loadData() {
        const seeks = [{
            WhereItems: [{
                FieldName: "#flowType",
                Operator: "=",
                FieldValues: '' + this.state.range,
            }],
            RelationSign: "AND"
        }];
        this.props.dispatch({
            type: `${daoName}/fetch`,
            payload: { daoName, page: 1, pageSize: 50, seeks }
        });

    }
    loadOptionData() {
        let options = []
        controls.map(c => {
            if (c.fetch) {
                let f = c.fetch;
                if (c.type === 'cascader-select') {
                    f.isCascader = true;
                }
                if (c.type !== 'search') {
                    options.push(f);
                }
            }
        })
        if (daoName && options.length > 0) {
            this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
        }
    }
    showModelHandler(isAdd) {
        this.setState({ mKey: this.state.mKey + 1 })
        let key = null
        if (!isAdd) {
            const len = this.props.selectedRowKeys.length;
            if (len === 0) {
                message.info('请选择要修改的认定关系！', 5);
                return;
            }
            key = this.props.selectedRowKeys[len - 1]
        }
        this.props.dispatch({
            type: `${daoName}/openEdit`,
            payload: { key }
        });
    }
    showModelHandler2() {
        let key = null
        const len = this.props.selectedRowKeys.length;
        if (len === 0) {
            message.error('请选择录入的任务流程！', 5);
            return;
        }
        if (len > 1) {
            message.error('不能为多条任务录入监测项目，请选择一条监测任务', 5);
            return;
        }
        key = this.props.selectedRowKeys[len - 1]
        this.setState({ rwid: key, cdisplay: "block", isShowBtn: true })
    }
    showModelHandler3(rwid) {
        // if (this.state.cdisplay === "none") {
        //     this.setState({ rwid: rwid, cdisplay: "block", isShowBtn: false })
        // } else {
        //     this.setState({ cdisplay: "none" })
        // }
        this.setState({ rwid: rwid, cdisplay: "block", isShowBtn: false })
    }
    //===============================================
    deleteHandler() {
        const keys = this.props.selectedRowKeys;
        const len = keys.length;
        if (len === 0) {
            message.info('请选择要删除的数据行！', 5);
            return;
        }
        Modal.confirm({
            title: '提示',
            content: `你确认要删除选中的${len}条数据吗？`,
            okText: '删除',
            cancelText: '取消',
            onOk: () => {
                this.props.dispatch({
                    type: `${daoName}/remove`,
                    payload: { daoName, keys },
                });
            }
        });
    }
    download(key) {
        const url = `/api/attachment/file${key}/${key}`;
        window.open(url, "blank")
    }
    edidOkHandler() {
        const at = this.refs.FileUpLoad.state.attIDs.length
        if (at === 0) {
            message.error('请按照格式正确上传一个附件', 5);
            return
        }
        if (at > 1) {
            message.error('仅支持上传一个附件，请删除其他多余附件', 5);
            return
        }
        const form = this.refs.diviForm.getForm()
        form.validateFields((err, values) => {
            if (!err) {
                let t = `${daoName}/submitData`
                controls.map(c => {
                    if (c.type === 'cascader-select') {
                        let vs = values[c.name];
                        if (vs.length > 0) {
                            values[c.name] = vs[vs.length - 1];
                        } else {
                            values[c.name] = null;
                        }
                    }
                    if (c.dataType === "number") {
                        values[c.name] = Number(values[c.name])
                    } else if (c.dataType === "date" || c.dataType === "datetime") {
                        const date = !values[c.name] ? null : new Date(values[c.name])
                        values[c.name] = date ? new Date(date.getFullYear(), date.getMonth(), date.getDate(), 8, 0, 0) : null
                    } else {
                        values[c.name] = values[c.name] === undefined ? null : values[c.name]
                    }
                    if (c.multiple || c.type === 'checkbox-group') {
                        values[c.name] = values[c.name].join(',');
                    }
                })
                values.UID = this.props.userID
                values.FID = Number(this.refs.FileUpLoad.state.attIDs[0])
                let datas = []
                datas.push(values)
                this.state.dataChange = true;
                this.props.dispatch({
                    type: t,
                    payload: { daoName, datas },
                })
                this.props.dispatch({
                    type: `${daoName}/setRecord`,
                    payload: { record: { FID: values.FID } },
                });
            }
        });
    };
    hideEditHandler() {
        const form = this.refs.diviForm.getForm();
        form.resetFields();
        if (this.state.dataChange) {
            this.props.dispatch({
                type: `${daoName}/reload`,
                payload: { daoName },
            });
            this.state.dataChange = false;
        }
        this.props.dispatch({
            type: `${daoName}/hideEdit`
        });
    };
    //延时一秒 设置isClick为false
    enableButton() {
        const that = this
        setTimeout(function () {
            that.setState({ isClick: false })
        }, 1000);
    }
    batchSubmitHandler(bType) {
        if (this.state.isClick) {
            return
        }
        this.setState({ isClick: true })
        const keys = this.props.selectedRowKeys;
        const len = keys.length;
        if (len === 0) {
            message.info('请选择要提交的流程信息！', 5);
            this.enableButton()
            return;
        }
        const list = this.props.list
        let runIDs = []
        let rwIDs = []
        let isOK = true
        list.map(row => {
            if (keys.find(key => row.ID === key)) {
                if (!row.FRID) {
                    isOK = false
                }
                runIDs.push(row.FRID)
                rwIDs.push(row.ID)
            }
        })
        if (!isOK) {
            message.error('流程提交失败，有未录入监测项目任务流程！', 5);
            this.enableButton()
            return;
        }
        if (list[0].BZ2 === "") {
            Modal.info({
                title: '提示',
                content: "申请人承若：如业务贷前、贷后阶段经分行核查存在违规行为，将移交分行纪委处理。如业务存续期内，涉及监管检查、内部审计检查问题，由经营单位承担相应责任。",
                okText: '已了解',
                onOk: () => {
                    bType = "agree"
                    this.props.dispatch({
                        type: `${daoName}/flowBatchSubmit`,
                        payload: { runIDs, userID: this.props.userID, desc: "", bType, rwIDs },
                    });
                }
            });
        }
        if (list[0].BZ2 !== "") {
            Modal.info({
                title: '提示',
                content: "申请人承若：如业务贷前、贷后阶段经分行核查存在违规行为，将移交分行纪委处理。如业务存续期内，涉及监管检查、内部审计检查问题，由经营单位承担相应责任。",
                okText: '已了解',
                onOk: () => {
                    let ts = `已有客户【${list[0].BZ2}】，进行承若过，是否继续提交？`
                    Modal.confirm({
                        title: '提示',
                        content: ts,
                        okText: '知道了',
                        cancelText: '再想想',
                        onOk: () => {
                            bType = "agree"
                            this.props.dispatch({
                                type: `${daoName}/flowBatchSubmit`,
                                payload: { runIDs, userID: this.props.userID, desc: "", bType, rwIDs },
                            });
                        }
                    });
                }
            });
        }
        this.cancelHandler()
        this.enableButton()
    }
    submitHandler(bType) {
        const { runID } = this.props.flowRunInfo
        bType = "agree"
        this.props.dispatch({
            type: `${daoName}/flowSubmit`,
            payload: { runID, userID: this.props.userID, desc: "", bType },
        });
        this.cancelHandler()
    }
    setExecutorHandler() {
        const { runID, currStep } = this.props.flowRunInfo
        const { checkVals } = this.state
        if (checkVals === "") {
            message.info("请您选择办理人！", 5)
        }
        this.props.dispatch({
            type: `${daoName}/setFolwExecutor`,
            payload: { runID, stepID: currStep, userIDstr: checkVals },
        });
    };
    sendBackHandler(bType) {
        const { runID, currStep } = this.props.flowRunInfo
        const { text } = this.state
        if (text === "") {
            message.info("请您填写退回意见！", 5)
            return
        }
        let bStep = 1
        let ts = "你确认要退回申请人吗"
        if (bType === "backPrev") {
            bStep = currStep - 1
            ts = "你确认要退回上一步吗"
        }
        Modal.confirm({
            title: '提示',
            content: ts,
            okText: '退回',
            cancelText: '取消',
            onOk: () => {
                this.props.dispatch({
                    type: `${daoName}/flowSendBack`,
                    payload: { runID, userID: this.props.userID, backStepID: bStep, desc: text },
                });
            }
        });
    }
    abortHandler() {
        if (this.state.isClick) {
            return
        }
        this.setState({ isClick: true })
        const keys = this.props.selectedRowKeys;
        const len = keys.length;
        if (len === 0) {
            message.info('请选择要中止的认定关系！', 5);
            this.enableButton()
            return;
        }
        const list = this.props.list
        let runIDs = []
        let isOK = true
        list.map(row => {
            if (keys.find(key => row.ID === key)) {
                if (!row.FRID) {
                    isOK = false
                }
                runIDs.push(row.FRID)
            }
        })
        Modal.confirm({
            title: '提示',
            content: `你确认要中止此流程吗？`,
            okText: '中止',
            cancelText: '取消',
            onOk: () => {
                this.props.dispatch({
                    type: `${daoName}/flowAbort`,
                    payload: { runIDs },
                });
            }
        });
        this.enableButton()
    }
    cancelHandler() {
        this.props.dispatch({
            type: `${daoName}/setFrid`,
            payload: { frid: 0 },
        });
    }
    doFlowHandler() {
        const { selectedRowKeys } = this.props
        if (selectedRowKeys.length === 0) {
            message.info("请选择要办理流程！", 5)
            return
        }
        const frid = selectedRowKeys[0]
        this.props.dispatch({
            type: `${daoName}/fetchFlowRunInfo`,
            payload: { runID: frid },
        });
    }
    rangeChangeHandler(e) {
        this.state.range = e.key
        this.loadData()
    }
    showStepHandler() {
        const len = this.props.selectedRowKeys.length;
        if (len === 0) {
            message.info('请选择要查看的流程信息！', 5);
            return;
        }
        const key = this.props.selectedRowKeys[len - 1]

        const list = this.props.list
        const index = list.findIndex(v => v.ID === key)

        const runID = list[index].FRID
        if (!runID) {
            message.info('选择的流程存在错误！', 5);
            return;
        }
        this.state.stepTitle = `监测任务：${list[index].JCRW}`
        this.props.dispatch({
            type: `${daoName}/fetchFlowRunInfo`,
            payload: { runID }
        });
    }
    hideStepHandler() {
        this.props.dispatch({
            type: `${daoName}/hideStep`,
            payload: {}
        });
    }
    onSelectChange(newList, delKeys) {
        let canEdit = false
        const oldKeys = this.props.selectedRowKeys;
        let keys = []
        oldKeys.forEach(key => {
            let isFind = false
            if (delKeys.find(key2 => key2 === key)) {
                isFind = true
            }
            if (!isFind) {
                keys.push(key)
            }
        })
        newList.forEach(row => {
            keys.push(row.ID)
        });
        const len = keys.length;
        if (len > 0) {
            const list = this.props.list
            let isOK = true
            list.map(row => {
                if (keys.find(key => row.ID === key)) {
                    if (row.step !== 1) {
                        isOK = false
                    }
                }
            })
            if (isOK) {
                canEdit = true
            }
        }
        this.setState({ canEdit, cdisplay: "none" })
    }
    banoChangeHandler(e) {
        const bano = e.target.value
        const cunm = this.state.cunm
        if (cunm && cunm != "" && bano && bano != "") {
            this.props.dispatch({
                type: `${daoName}/fetchAcno`,
                payload: { cunm, bano }
            });
        }
    }
    renderStep() {
        const { flowRunInfo } = this.props
        const steps = flowRunInfo.stepList.map(s => {
            let desc = "未开始"
            let iszz = false
            if (flowRunInfo.state === '2' && flowRunInfo.currStep === s.id) {
                desc = "已中止"
                iszz = true
            } else if (s.state === '1') {
                desc = "办理中..."
            } else if (s.state === '2') {
                desc = "已办理"
            }
            let content = []
            s.executors.map(e => {
                let color = ""
                if (e.desc === "待办..." || e.desc === "未办") {
                    color = "gray"
                } else if (e.desc.substring(0, 2) === "中止" || e.desc === "管理员强制提交") {
                    color = "#FA541C"
                } else {
                    color = "#0D993A"
                }
                let c = <div key={e.id} ><span>{`${e.name}(${e.department})：`}</span> <br />
                    <span style={{ color: color }}>{e.desc}
                    </span>
                </div>
                content.push(c)
            })
            const descTag = <div style={{ maxHeight: "200px", overflow: "auto" }}>{content}</div>
            return <Step key={s.id} title={s.name + `【` + desc + `】`} description={descTag} />
        })
        let status = "process"
        if (flowRunInfo.state === "1") {
            status = "finish"
        } else if (flowRunInfo.state === "2") {
            status = "error"
        } else {
            const step = flowRunInfo.stepList[flowRunInfo.currStep - 1]
            if (step.appointer && step.appointer.length > 0 && step.executors.length == 0) {
                status = "wait"
            }
        }
        const current = flowRunInfo.currStep - 1
        return <Steps direction="vertical" current={current} status={status}>{steps}</Steps>
    }
    renderList() {
        const columns = [
            { title: "当前进度", key: "StepName", render: data => renderStep(data), width: 170, dispaly: true },
            {
                title: '', width: 120, key: 'FID', caption: "FID",
                render: d => (
                    <span>
                        <Tag color={"#1296db"} >
                            <a onClick={this.download.bind(this, d.FID)}>下载附件</a>
                        </Tag>
                    </span>
                ),
                dispaly: true, export: false
            },
            {
                title: '', width: 120, key: 'RWID', caption: "RWID",
                render: d => (
                    <span>
                        <Tag color={"#1296db"} >
                            <a onClick={this.showModelHandler3.bind(this, d.ID)}>查看项目</a>
                        </Tag>
                    </span>
                ),
                dispaly: true, export: false
            },
            { title: '监测任务名称', dataIndex: 'JCRW', key: 'JCRW', width: 300, sorter: true, dispaly: true, filter: true, export: true },
            { title: '所属条线', width: 150, sorter: true, key: 'SSTX', dataIndex: 'SSTXCaption', filter: true, dispaly: true, export: true },
            { title: '收益承诺日期', dataIndex: 'CNRQ', key: 'CNRQ', width: 150, sorter: true, dispaly: true, filter: true, export: true },
            { title: '经营单位', dataIndex: 'JYDW', key: 'JYDW', width: 120, sorter: true, dispaly: true, filter: true, export: true },
            { title: '支行负责人', dataIndex: 'FZR', key: 'FZR', width: 150, sorter: true, dispaly: true, filter: true, export: true },
            { title: '客户经理1', dataIndex: 'KHJL1', key: 'KHJL1', width: 120, sorter: true, dispaly: true, filter: true, export: true },
            { title: '客户经理2', dataIndex: 'KHJL2', key: 'KHJL2', width: 120, sorter: true, dispaly: true, filter: true, export: true },
            { title: '客户经理3', dataIndex: 'KHJL3', key: 'KHJL3', width: 120, sorter: true, dispaly: true, filter: true, export: true },
            { title: '备注', dataIndex: 'BZ', key: 'BZ', width: 250, sorter: true, dispaly: true, filter: true, export: true },
        ];
        let { permID, showStep, showEdit, record, userID, userName, pOrgID, selectedRowKeys } = this.props
        let { range, canEdit, isClick } = this.state
        let attIDs = []
        if (record.FID && record.FID !== 0) {
            attIDs = [record.FID]
        }
        const menu = <Menu onClick={this.rangeChangeHandler.bind(this)}>
            <Menu.Item key="firstdoing">在办</Menu.Item>
            <Menu.Item key="firstdone">已办</Menu.Item>
            <Menu.Item key="firstall">全部</Menu.Item>
        </Menu>
        const butts = <ButtonGroup style={{ zIndex: 0 }}>
            <Dropdown overlay={menu} trigger={['click']}>
                <Button type="ghost" style={{ margin: 5 }}>
                    {range === "firstdoing" ? "在办" : range === "firstdone" ? "已办" : "全部"}<Icon type="down" />
                </Button>
            </Dropdown>
            {range === "firstdoing" ? <Button onClick={this.showModelHandler.bind(this, true)}>新增</Button> : null}
            {range === "firstdoing" ? <Button onClick={this.showModelHandler2.bind(this)}>编辑监测项目</Button> : null}
            {range === "firstdoing" && canEdit ? <Button onClick={this.deleteHandler.bind(this)}>删除</Button> : null}
            <Button onClick={this.showStepHandler.bind(this)}>查看进度</Button>
            {range === "firstdoing" ? <Button onClick={this.batchSubmitHandler.bind(this)} disabled={isClick}>提交</Button> : null}
        </ButtonGroup>
        return (
            <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
                <div>
                    <div className={styles.create}>
                        {butts}
                    </div>
                    <Modal key={this.state.mKey} ref="Modal" title="新增任务" width={700} visible={showEdit}
                        onOk={this.edidOkHandler.bind(this)}
                        onCancel={this.hideEditHandler.bind(this)}
                        maskClosable={true}
                        footer={[
                            <Button key="close" type="ghost" onClick={this.hideEditHandler.bind(this)}>关闭</Button>,
                            <Button key="submit" type="primary" onClick={this.edidOkHandler.bind(this)}>保存</Button>
                        ]}
                    >
                        <EditFrom ref="diviForm" daoName={daoName} controls={controls} record={record} />
                        <FileUpLoad ref="FileUpLoad"
                            name="qzl"
                            attIDs={attIDs}
                        />
                    </Modal>
                    <DataTable ref="diviTable" daoName={daoName} columns={columns} controls={controls2} permID={permID} onSelectChange={this.onSelectChange.bind(this)} multiSelect={false} />
                    {showStep ? <Modal key={this.state.mKey + 1} title={this.state.stepTitle} width={400} visible={showStep} onCancel={this.hideStepHandler.bind(this)}
                        footer={null}
                    >
                        {this.renderStep()}
                    </Modal> : null}
                    <div style={{ display: this.state.cdisplay, marginTop: "20px" }}>
                        <Card title="监测项目" >
                            <SYJCLRSQ_MXForm rwid={this.state.rwid} isShowBtn={this.state.isShowBtn} />
                        </Card>
                    </div>
                </div>
            </div>
        )
    }
    render() {
        return this.renderList()
    }
}
function mapStateToProps(state) {
    const { showEdit, showStep, record, list, selectedRowKeys, keyName, flowRunInfo, frid } = state[daoName];
    const { userID, orgID, pOrgID, popedomTypes, RDDate, userName, UserNo } = state.menus;
    return {
        loading: state.loading.models[daoName],
        userID,
        orgID,
        pOrgID, userName, UserNo,
        popedomTypes,
        list,
        showEdit,
        showStep,
        selectedRowKeys,
        keyName,
        record,
        flowRunInfo,
        frid,
        RDDate
    }
}
SYJCLRSQForm = connect(mapStateToProps)(SYJCLRSQForm)
export default SYJCLRSQForm;
let render = (props) => React.createElement(SYJCLRSQForm, props);
let f = new Factory()
f.set("SYJCLRSQForm", render)
